package upc.interceptor;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import upc.model.UserDO;
import upc.util.CommonUtil;
import upc.util.JsonData;
import upc.util.JwtUtil;


public class PublisherInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserDO> threadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }

        String accessToken = request.getHeader("token");
        if (StringUtils.isBlank(accessToken)) {
            accessToken = request.getParameter("token");
        }


        if (StringUtils.isNotBlank(accessToken)) {
            Claims claims = JwtUtil.checkPublisherJWT(accessToken);
            if (claims == null) {
                //未登录
                CommonUtil.sendJsonMessage(response, JsonData.buildError(""));
                return false;
            }

            Long accountNo = Long.parseLong(claims.get("id").toString());
            String username = (String) claims.get("name");
            String phone = (String) claims.get("phone");

            UserDO loginUser = UserDO.builder()
                    .id(accountNo)
                    .phone(phone)
                    .name(username)
                    .build();

            //request.setAttribute("loginUser",loginUser);
            //通过threadlocal
            threadLocal.set(loginUser);
            return true;
        }

        CommonUtil.sendJsonMessage(response,JsonData.buildError(""));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        threadLocal.remove();
    }
}
